package com.tanhua.server.peachblossom.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.PeachBlossomApi;
import com.tanhua.dubbo.server.pojo.PeachBlossom;
import com.tanhua.server.peachblossom.enums.SexEnum;
import com.tanhua.server.peachblossom.pojo.User;
import com.tanhua.server.peachblossom.pojo.UserInfo;
import com.tanhua.server.peachblossom.utils.UserThreadLocal;
import com.tanhua.server.peachblossom.vo.PeachBlossomResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

@Service
public class PeachBlossomService {

    @Autowired
    protected FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Reference(version = "1.0.0")
    private PeachBlossomApi peachBlossomApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private int number = 10;


    private static final ObjectMapper MAPPER = new ObjectMapper();

    public PeachBlossomResult getPeachBlossom() {
        //抓取当前用户的信息；
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        //获取当前用户的性别
        UserInfo userInfo = this.userInfoService.queryUserInfoById(userId);
        Integer sex = userInfo.getSex().getValue();

        //检查有没有剩余次数的
        String PEACH_USER_TIMES = "PEACH_" + userId;
        String peachBlossomListKey = "peachBlossomList_" + userId;
        if (!this.redisTemplate.hasKey(PEACH_USER_TIMES)) {
            //默认 剩余次数10次 有效期 1day
            this.redisTemplate.opsForValue().set(PEACH_USER_TIMES, "10", Duration.ofDays(1));
            //获取 随机的语音 有效期 1day
            List<PeachBlossom> peachBlossomList = this.peachBlossomApi.getPeachBlossomList(userId, sex);
            List<Integer> integerList = new ArrayList<>();
            for (PeachBlossom peachBlossom : peachBlossomList) {
                integerList.add(Long.valueOf(peachBlossom.getUserId()).intValue());
            }
            this.redisTemplate.opsForValue().set(peachBlossomListKey, String.valueOf(integerList));
        }

        int count = Integer.parseInt(this.redisTemplate.opsForValue().get(PEACH_USER_TIMES));
        String strs = this.redisTemplate.opsForValue().get(peachBlossomListKey);
        String ss = strs.substring(1, strs.length() - 1);
        String[] splits = ss.split(",");
        List<Long> userIdList = new ArrayList<>();
        for (String split : splits) {
            Long n = Long.parseLong(split.trim());
            userIdList.add(n);
        }


        //剩余次数 不能为0
        if ( count>0 ) {
            Long id = userIdList.get(number - count);
            //获得 语音用户的信息
            UserInfo peachUserInfo = userInfoService.queryUserInfoById(id);
            //封装 对方的信息
            PeachBlossomResult peachBlossomResult = new PeachBlossomResult();
            peachBlossomResult.setRemainingTimes(count - 1);
            peachBlossomResult.setUserId(id);
            peachBlossomResult.setAge(peachUserInfo.getAge());
            peachBlossomResult.setAvatar(peachUserInfo.getLogo());
            peachBlossomResult.setNickname(peachUserInfo.getNickName());
            PeachBlossom url = this.peachBlossomApi.queryPeach(id, peachUserInfo.getSex().getValue());
            peachBlossomResult.setGender(peachUserInfo.getSex().getValue() == 1?"man":"woman");
            peachBlossomResult.setSoundUrl(url.getSoundUrl());
            //剩余次数 -1
            this.redisTemplate.opsForValue().decrement(PEACH_USER_TIMES);
            return peachBlossomResult;
        }else{
            return null;
        }
    }

    public Boolean saveSound(MultipartFile soundFile) {
        User user = UserThreadLocal.get();
        Long userId = user.getId();
        UserInfo userInfo = userInfoService.queryUserInfoById(userId);
        SexEnum sexEnum = userInfo.getSex();
        Integer sex = sexEnum.getValue();
        PeachBlossom peachBlossom = this.peachBlossomApi.queryPeach(userId, sex);
        System.out.println("soundFile.getName() = " + soundFile.getName());

        if (peachBlossom == null) {
            try {
                StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(),
                        StringUtils.substringAfter(soundFile.getOriginalFilename(), "."), null);

                String group = storePath.getGroup();
                String path = storePath.getPath();
                redisTemplate.opsForValue().set("PEACH_GROUP_" + userId, group);
                redisTemplate.opsForValue().set("PEACH_PATH_" + userId, path);

                String url = fdfsWebServer.getWebServerUrl() + "/" + storePath.getFullPath();
                Boolean savepeach = this.peachBlossomApi.savePeach(url, userId, sex);
                return savepeach;

            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        } else {
            try {
                String PEACH_GROUP = this.redisTemplate.opsForValue().get("PEACH_GROUP_" + userId);
                String PEACH_PATH = this.redisTemplate.opsForValue().get("PEACH_PATH_" + userId);
                //删除 旧文件
                storageClient.deleteFile(PEACH_GROUP, PEACH_PATH);
                //上传 新文件
                StorePath storePath = storageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(),
                        StringUtils.substringAfter(soundFile.getOriginalFilename(), "."), null);
                String path = storePath.getPath();
                String group = storePath.getGroup();
                redisTemplate.opsForValue().set("PEACH_GROUP_" + userId, group);
                redisTemplate.opsForValue().set("PEACH_PATH_" + userId, path);
                String url = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
                Boolean updatePeach = this.peachBlossomApi.updatePeach(url, userId, sex);
                return updatePeach;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;

        }
    }
}
